package sys.spvisor.core.service.project;

import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import sys.spvisor.core.common.ModifyPeopleException;
import sys.spvisor.core.common.PermissionException;
import sys.spvisor.core.dao.people.TPeopleMapper;
import sys.spvisor.core.dao.project.TFileCheckProcessMapper;
import sys.spvisor.core.dao.project.TFileFormMapper;
import sys.spvisor.core.dao.project.TProjectMapper;
import sys.spvisor.core.dao.project.TProjectPeopleMapper;
import sys.spvisor.core.dao.project.TSendCardMapper;
import sys.spvisor.core.entity.people.TPeople;
import sys.spvisor.core.entity.people.TPeopleExample;
import sys.spvisor.core.entity.people.TPeopleExample.Criteria;
import sys.spvisor.core.entity.project.PeopleProjectBigClass;
import sys.spvisor.core.entity.project.TFileCheckProcess;
import sys.spvisor.core.entity.project.TFileCheckProcessExample;
import sys.spvisor.core.entity.project.TFileForm;
import sys.spvisor.core.entity.project.TFileFormExample;
import sys.spvisor.core.entity.project.TProject;
import sys.spvisor.core.entity.project.TProjectExample;
import sys.spvisor.core.entity.project.TProjectPeople;
import sys.spvisor.core.entity.project.TProjectPeopleExample;
import sys.spvisor.core.entity.project.TSendCard;
import sys.spvisor.core.entity.project.TSendCardExample;

@Service
public class DispatchService {
	
	@Autowired 
	TProjectMapper tProjectMapper;
	@Autowired
	TPeopleMapper tPeopleMapper;
	@Autowired
	TProjectPeopleMapper projectPeopleMapper;
	@Autowired
	TFileFormMapper fileFormMapper;
	@Autowired
	TFileCheckProcessMapper tFileCheckProcessMapper;
	@Autowired
	TSendCardMapper tSendCardMapper;
	//人员派遣选人
	@Transactional
	public List<PeopleProjectBigClass> selectPeople() {
		List<PeopleProjectBigClass> result = new ArrayList<PeopleProjectBigClass>();
		TPeopleExample tPeopleExample = new TPeopleExample();
		Criteria criteria1 = tPeopleExample.createCriteria();
		criteria1.andPeoStationDescLike("%待岗");
		List<TPeople> list1 = tPeopleMapper.selectByExample(tPeopleExample);
		tPeopleExample.clear();
		
		Criteria criteria2 = tPeopleExample.createCriteria();
		criteria2.andPeoStationDescEqualTo("休假");
		List<TPeople> list2 = tPeopleMapper.selectByExample(tPeopleExample);
		tPeopleExample.clear();
		
		Criteria criteria3 = tPeopleExample.createCriteria();
		criteria3.andPeoStationDescNotLike("%待岗");
		criteria3.andPeoStationDescNotEqualTo("休假");
		criteria3.andPeoStationDescNotEqualTo("离职");
		List<TPeople> list3 = tPeopleMapper.selectByExample(tPeopleExample);
		tPeopleExample.clear();
		
		list1.addAll(list2);
		list1.addAll(list3);
		//与项目人员表连接找所在项目
		for(TPeople tPeople : list1){
			PeopleProjectBigClass peoProBigCla = new PeopleProjectBigClass();
			peoProBigCla.setPeople(tPeople);
			TProjectPeopleExample tProjectPeopleExample = new TProjectPeopleExample();
			sys.spvisor.core.entity.project.TProjectPeopleExample.Criteria tProjectPeopleCriteria = tProjectPeopleExample.createCriteria();
			tProjectPeopleCriteria.andPpPeopleidEqualTo(tPeople.getPeoId());
			List<TProjectPeople> tProjectPeopleList = projectPeopleMapper.selectByExample(tProjectPeopleExample);
			tProjectPeopleExample.clear();
			if(tProjectPeopleList.size() == 0){
				result.add(peoProBigCla);
			}
			else{
				peoProBigCla.setProjectPeople(tProjectPeopleList.get(0));
				Integer proId = tProjectPeopleList.get(0).getPpMsgid();
				TProjectExample tProjectExample = new TProjectExample();
				sys.spvisor.core.entity.project.TProjectExample.Criteria tProjectCriteria = tProjectExample.createCriteria();
				tProjectCriteria.andProIdEqualTo(proId);
				List<TProject> tProjects = tProjectMapper.selectByExample(tProjectExample);
				tProjectExample.clear();
				if(tProjects.size() > 0){
					peoProBigCla.setProject(tProjects.get(0));
				}
				result.add(peoProBigCla);	
			}
		}
		return result;
	}
	
	@Transactional
	public List<TProjectPeople> getPeopleByProjectIdAndPost(Integer projectId,String post) {
		TProjectPeopleExample tProjectPeopleExample = new TProjectPeopleExample();
		sys.spvisor.core.entity.project.TProjectPeopleExample.Criteria criteria = tProjectPeopleExample.createCriteria();
		criteria.andPpMsgidEqualTo(projectId);
		criteria.andPpProRoleDescEqualTo(post);
		return projectPeopleMapper.selectByExample(tProjectPeopleExample);
	}
	
	@Transactional
	public List<TProjectPeople> getPeopleInProByProjectIdAndPost(Integer projectId,String post) {
		TProjectPeopleExample tProjectPeopleExample = new TProjectPeopleExample();
		sys.spvisor.core.entity.project.TProjectPeopleExample.Criteria criteria = tProjectPeopleExample.createCriteria();
		criteria.andPpMsgidEqualTo(projectId);
		criteria.andPpProRoleDescEqualTo(post);
		criteria.andPpStatusEqualTo("O");
		return projectPeopleMapper.selectByExample(tProjectPeopleExample);
	}
	
	@Transactional
	public void dispatchGroupLeaderAndMemberByProjectIdAndPost(Integer projectId,String post,List<TProjectPeople> tProjectPeoples) throws PermissionException, ModifyPeopleException {
		//先获取项目开始时间
		TProject tProject = tProjectMapper.selectByPrimaryKey(projectId);
		Date date = tProject.getBegintime();
		if(new java.util.Date().getTime() > date.getTime())
			throw new PermissionException("项目已开始，无法派遣，请到人员变更模块进行人员变更！");
		if(projectId != null && tProjectPeoples != null){
			TProjectPeopleExample tProjectPeopleExample = new TProjectPeopleExample();
			sys.spvisor.core.entity.project.TProjectPeopleExample.Criteria criteria = tProjectPeopleExample.createCriteria();
			criteria.andPpMsgidEqualTo(projectId);
			criteria.andPpProRoleDescEqualTo(post);
			List<TProjectPeople> existProjectPeoples = projectPeopleMapper.selectByExample(tProjectPeopleExample);
			boolean[] flag = new boolean[existProjectPeoples.size()];
			for(TProjectPeople tProjectPeople : tProjectPeoples){
				int i = 0;
				for(i = 0; i< existProjectPeoples.size(); i++){
					if(tProjectPeople.getPpPeopleid() == existProjectPeoples.get(i).getPpPeopleid()){
						flag[i] = true;
						break;
					}
				}
				//insert
				if(i == existProjectPeoples.size()){
					projectPeopleMapper.insert(tProjectPeople);
				}
			}
			for(int i = 0; i< existProjectPeoples.size(); i++){
				if(flag[i] == false)
					projectPeopleMapper.deleteByPrimaryKey(existProjectPeoples.get(i).getProjectPeopleId());
			}
			
		}
		else{
			throw new ModifyPeopleException("派遣失败");
		}
	}
	
	@Transactional
	public void saveProjectPeopleByProjectIdAndPost(Integer projectId,String post,List<TProjectPeople> tProjectPeoples){
		for(TProjectPeople tProjectPeople : tProjectPeoples){
			//update
			if(tProjectPeople.getProjectPeopleId() != null){
				projectPeopleMapper.updateByPrimaryKey(tProjectPeople);
				continue;
			}
			//insert
			projectPeopleMapper.insert(tProjectPeople);
			
		}
	}
	
	public void deleteByProjectPeopleId(Integer projectPeopleId){
		projectPeopleMapper.deleteByPrimaryKey(projectPeopleId);
	}

	@Transactional
	public List<TFileForm> selectDispatchFileByProjectId(Integer projectId){
		List<TFileForm> TFileForms = new ArrayList<TFileForm>();
		if(projectId == null)
			return TFileForms;
		TFileFormExample example = new  TFileFormExample();
		sys.spvisor.core.entity.project.TFileFormExample.Criteria criteria = example.createCriteria();
		criteria.andFileFormProjectIdEqualTo(projectId);
		criteria.andFileFormTypeEqualTo("人员派遣");
		List<TFileForm> selectTFileForms = fileFormMapper.selectByExample(example);
		example.clear();
		addExistsFile("技术交底会议纪要",selectTFileForms,TFileForms);
		//往TFileForms添加可有文件
		for(TFileForm tFileForm : selectTFileForms){
			TFileForms.add(tFileForm);
		}
		return TFileForms;
	}
	//往TFileForms添加必有文件
	private void addExistsFile(String fileName,List<TFileForm> selectTFileForms,List<TFileForm> TFileForms){
		for(TFileForm tFileForm : selectTFileForms){
			if(tFileForm.getFileFormName().equals(fileName)){
				TFileForms.add(tFileForm);
				selectTFileForms.remove(tFileForm);
				return;
			}
		}
		TFileForm fileForm = new TFileForm();
		fileForm.setFileFormName(fileName);
		TFileForms.add(fileForm);
	}
	
	
	@Transactional
	public List<TSendCard> getSendCardByProjectId(Integer projectId) {
		TSendCardExample tSendCardExample = new TSendCardExample();
		sys.spvisor.core.entity.project.TSendCardExample.Criteria criteria = tSendCardExample.createCriteria();
		criteria.andTSendProjectIdEqualTo(projectId);
		return tSendCardMapper.selectByExample(tSendCardExample);
	}
	@Transactional
	public void submitFileAndSendcard(Integer projectId, String fileNameTotal,TSendCard sendCard, Map<String, MultipartFile> fileMap,String userName,long userId) throws PermissionException, IOException{
		String[] name = fileNameTotal.split("&");
		//文件上传
		int index = 0;
		TFileFormExample tFileFormExample = new TFileFormExample();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile mf 	= entity.getValue();
			System.out.println(mf.getOriginalFilename());
			if(!mf.getOriginalFilename().equals("")){
				//判断上传文件里有没有此文件
				sys.spvisor.core.entity.project.TFileFormExample.Criteria ifExistCriteria = tFileFormExample.createCriteria();
				ifExistCriteria.andFileFormTypeEqualTo("人员派遣");
				ifExistCriteria.andFileFormNameEqualTo(name[index]);
				ifExistCriteria.andFileFormProjectIdEqualTo(projectId);
				List<TFileForm> fileForms = fileFormMapper.selectByExample(tFileFormExample);
				tFileFormExample.clear();
				//若没有
				if(fileForms.size() == 0){
					TFileForm tPlanForm = new TFileForm();
					tPlanForm.setFileFormFilename(mf.getOriginalFilename());
					tPlanForm.setFileFormContent(mf.getBytes());
					tPlanForm.setFileFormName(name[index]);
					tPlanForm.setFileFormPeople(userName);
					tPlanForm.setFileFormPeopleId((int)userId);
					tPlanForm.setFileFormDate(new Date(new java.util.Date().getTime()));
					tPlanForm.setFileFormType("人员派遣");
					tPlanForm.setFileFormProjectId(projectId);
					tPlanForm.setFileFormCurrentStatus("W");
					tPlanForm.setFileFormCurrentStatusNum(0);
					tPlanForm.setFileFormNotpassTimes(0);
					fileFormMapper.insert(tPlanForm);
					//刚上传的文件状态默认待审核，后面判断是否需要审核，若不需要则改为已上传
					changeStatusIfNoNeedCheck("Dispatch",name[index],tPlanForm);
					
				}
				//若有
				//判断是否审核未通过或者已上传，若是则更新
				else {
					TFileForm tff = fileForms.get(0);
					if(tff.getFileFormCurrentStatus().equals("W")||tff.getFileFormCurrentStatus().equals("P"))
						throw new PermissionException(name[index]+"当前状态已无法操作！");
					else{
						tff.setFileFormFilename(mf.getOriginalFilename());
						tff.setFileFormContent(mf.getBytes());
						tff.setFileFormName(name[index]);
						tff.setFileFormPeople(userName);
						tff.setFileFormPeopleId((int)userId);
						tff.setFileFormDate(new Date(new java.util.Date().getTime()));
						tff.setFileFormProjectId(projectId);
						tff.setFileFormCurrentStatus("W");
						tff.setFileFormCurrentStatusNum(0);
						if(tff.getFileFormCurrentStatus().equals("D"))
							tff.setFileFormNotpassTimes(0);
						else{
							tff.setFileFormNotpassTimes(tff.getFileFormNotpassTimes()+1);
						}
						fileFormMapper.updateByPrimaryKey(tff);
						changeStatusIfNoNeedCheck("Dispatch",name[index],tff);
					}
						
				}
			}
			index++;
		}//文件上传结束
		//派遣单上传
		TProject project = tProjectMapper.selectByPrimaryKey(projectId);
		sendCard.settSendProjectId(projectId);
		sendCard.settSendProjectName(project.getProjectName());
		List<TSendCard> sendCards = getSendCardByProjectId(projectId);
		if(sendCards.size() > 0){
			sendCard.settSendId(sendCards.get(0).gettSendId());
			tSendCardMapper.updateByPrimaryKey(sendCard);
		}
		else
			tSendCardMapper.insert(sendCard);
	}
	
	private void changeStatusIfNoNeedCheck(String belong, String filename, TFileForm fileForm){
		TFileCheckProcessExample tFileCheckProcessExample = new TFileCheckProcessExample();
  		sys.spvisor.core.entity.project.TFileCheckProcessExample.Criteria criteria = tFileCheckProcessExample.createCriteria();
  		criteria.andFileBelongToEqualTo(belong);
  		criteria.andFileNameEqualTo(filename);
  		criteria.andFileCurrentStatusEqualTo(1);
  		List<TFileCheckProcess> fcp = tFileCheckProcessMapper.selectByExample(tFileCheckProcessExample);
  		tFileCheckProcessExample.clear();
  		if(fcp == null || fcp.size() == 0){
  			fileForm.setFileFormCurrentStatus("D");
  			fileFormMapper.updateByPrimaryKey(fileForm);
  		}
  	}
	
}
